<?php
declare (strict_types = 1);
namespace app\attachment\controller;
use OSS\OssClient;
use OSS\Core\OssException;
class AliyunOss extends Base
{
    private $accessKeyId = 'LTAI4FgQVBG6DAuLg8PVaaGP';
    private $accessKeySecret = '2XdqVbHsRk2YQPg5cDNcTENzilyS4U';
    // private $endpoint = 'http://fortuna.oss-cn-beijing.aliyuncs.com';
    private $endpoint = 'http://image.goingmerry.cn';
    private $bucket = 'fortuna';
    private $dir = 'test/';

    private $ossClient = null;

    protected function initialize()
    {
        parent::initialize();
        try {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, true);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }
    // 回调接口
    public function callback() {
        // 保存数据库
        // $this->model->save();
    }
    // 删除文件对象
    public function delete_object() {
        $url = $this->request->get('url', null);
        $object = $this->getObjectName($url);
        try {
            $this->ossClient->deleteObject($this->bucket, $object);
            return json('删除成功！');
        } catch (OssException $e) {
            return json($e->getMessage(),500);
        }
    }
    // 构建表单上传(PostObject)的policy域
    public function policy() {
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);


        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition; 

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0=>'starts-with', 1=>'$key', 2=>$this->dir);
        $conditions[] = $start; 


        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->accessKeySecret, true));

        $response = array();
        $response['accessid'] = $this->accessKeyId;
        $response['host'] = $this->endpoint;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        // $response['callback'] = $base64_callback_body;
        $response['dir'] = $this->dir;  // 这个参数是设置用户上传文件时指定的前缀。
        echo json_encode($response);
    }
    // 
    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
    // 获取object
    protected function getObjectName($url) {
        return substr($url,strlen($this->endpoint.'/'));
    }
}
